// 提交的时候是否全部验证通过
function checkForm() {

    var result = "";

    // 判断生成的json
    if ($.trim($('.reId').val()).length == 0) {
        result += 'fail';
        $('#js-selected-acup-info').html("* 请选择穴位和资源！").css("color", "red");
    }
    // 判断名称
    if ($.trim($('.rebinName').val()).length == 0) {
        result += 'fail';
        $('.tiprebinName').html("* 不能为空！").css("color", "red");
    } else {
        $('.tiprebinName').html("√").css("color", "green");
    }
    // 判断说明
    if ($.trim($('.rebinInstruct').val()).length == 0) {
        result += 'fail';
        $('.tiprebinInstruct').html("* 不能为空！").css("color", "red");
    } else {
        $('.tiprebinInstruct').html("√").css("color", "green");
    }

    if (result != "") {
        return false;
    }
    return true;
}
// 点击刷新网页
$('.clearForm').on('click', function () {
    window.location.reload();
});

// 点击新增按钮，隐藏更新按钮
function showAndHide() {
    $("#updateBtn").hide();
    $("#resVideo").hide();
    getAcupuncturePoint();
    getResources();
    $('#js-selected-res').selected('disable');
}

// 加载穴位下拉搜索框
function getAcupuncturePoint() {
    $.ajax({
        type: "POST",
        url: "/resourceCombinationController/findAcupuncturePoint",
        success: function (data) {
            for (var i = 0; i < data.acupuncturePointList.length; i++) {
                $("#js-selected-acup").append('<option value=" ' + data.acupuncturePointList[i].acupId + '">' + data.acupuncturePointList[i].acupName + '</option>');
            }
        }
    });
}

// 加载资源下拉搜索框
function getResources() {
    $.ajax({
        type: "POST",
        url: "/resourceCombinationController/findWebresource",
        success: function (data) {
            for (var i = 0; i < data.webresourceList.length; i++) {
                $('#js-selected-res').append("<option value=" + data.webresourceList[i].reid + ">" + data.webresourceList[i].rname + "</option>");
            }
        }
    });
}


var arr = [];  // 保存生成的json


// 穴位下拉框改变事件
$('#js-selected-acup').on('change', function () {
    var acup = $('#js-selected-acup');
    if (acup.val() === null || acup.val() === undefined || acup.val() === '' || acup.val() == 0) {
        return;
    } else {
        $('#js-selected-res').selected('enable');
    }
});

// 资源下拉框改变事件
$('#js-selected-res').on('change', function () {
    var acup = $('#js-selected-acup');
    var res = $('#js-selected-res');
    if (res.val() === null || res.val() === undefined || res.val() === '' || res.val() == 0) {
        return;
    } else {
        $('#js-selected-acup-info').append(
            "<div class='am-btn am-btn-secondary am-round' style='margin: 2px' onclick='delThis(" + res.val() + "," + acup.val() + ",this)'>"
            + acup.children('option:selected').text() + "：" + $(this).children('option:selected').text()
            + "</div>"
        );
        var obj = {"resid": $(this).val(), "acupid": acup.val()};
        arr.push(obj);
        if (arr.length > 0) {
            $(".reId").val(JSON.stringify(arr));
        }
        console.log(JSON.stringify(arr));
        $('#js-selected-res').selected('disable');
    }
});

// 移除当前元素，用来移除生成的dom
//rid：资源id   acid ：穴位id
function delThis(rid, acid, dom) {
    console.log(rid + '----' + acid);
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].resid == rid && arr[i].acupid == acid) {
            arr.splice(i, 1);
        }
    }
    $(".reId").val(JSON.stringify(arr));
    console.log('-----------' + JSON.stringify(arr));
    dom.remove();
}

// 添加
$('#addBtn').on('click', function () {
    if (confirm("确定添加组合资源？")) {
        if (checkForm()) {
            $.ajax({
                type: "POST",
                url: "/resourceCombinationController/addResourceCombination",
                dataType: "json",
                data: $("#dataForm").serialize(),
                success: function (data) {
                    if (data.result == "success") {
                        alert("添加成功！");
                        window.location.reload();
                    } else {
                        alert("添加失败！");
                    }
                },
                error: function () {
                    alert("发送请求失败！");
                }
            });
        } else {
            alert("提交失败，请检查红色提示部分！");
        }
    }
});

// 获得一条信息并显示
function showFun(rebinId) {
    getAcupuncturePoint();
    getResources();
    $("#addBtn").hide();
    $('#js-selected-res').selected('disable');
    if (!$.AMUI.support.mutationobserver) {
        $selected.trigger('changed.selected.amui');
    }
    $.ajax({
        type: "GET",
        url: "/resourceCombinationController/findOneResourceCombination?rebinId=" + rebinId,
        dataType: "json",
        success: function (data) {
            // 唯一标识（用于保存修改的时候的id）
            $(".rebinId").val(data.webres.rebinId);
            // json处理
            $(".reId").val(data.webres.reId);
            var json = JSON.parse(data.webres.reId); // string--json
            arr = json;
            for (var i = 0; i < json.length; i++) {
                $.ajax({
                    type: "GET",
                    url: "/resourceCombinationController/getNameResourceCombination?resid=" + json[i].resid + "&acupid=" + json[i].acupid,
                    success: function (data) {
                        $('#js-selected-acup-info').append(
                            "<div class='am-btn am-btn-secondary am-round' style='margin: 2px' onclick='delThis(" + data.webres.reid + "," + data.acup.acupId + ",this)'>"
                            + data.acup.acupName + "：" + data.webres.rname
                            + "</div>"
                        );
                    },
                    error: function () {
                        alert("发送请求失败！");
                    }
                });
            }
            // 名称
            $(".rebinName").val(data.webres.rebinName);
            // 会员可看状态
            if (data.webres.toVip == 1) {
                $(".toVip:eq(0)").attr("checked", "checked");
            } else {
                $(".toVip:eq(1)").attr("checked", "checked");
            }
            // 学员可看状态
            if (data.webres.toStudent == 1) {
                $(".toStudent:eq(0)").attr("checked", "checked");
            } else {
                $(".toStudent:eq(1)").attr("checked", "checked");
            }
            // 说明
            $(".rebinInstruct").val(data.webres.rebinInstruct);
            // 备注
            $(".rebinNote").val(data.webres.rebinNote);
        },
        error: function () {
            alert("发送更新请求失败！");
        }
    });
}

// 更新
function updateFun() {
    if (confirm("您确定更新数据？")) {
        if (checkForm()) {
            $.ajax({
                type: "POST",
                url: "/resourceCombinationController/updateResourceCombination",
                dataType: "json",
                data: $("#dataForm").serialize(),
                success: function (data) {
                    if (data.result == "success") {
                        alert("更新成功！");
                        window.location.reload();
                    } else {
                        alert("更新失败！");
                    }
                },
                error: function () {
                    alert("发送请求失败！");
                }
            });
        } else {
            alert("更新失败，请检查红色提示部分！");
        }
    }
}

// 删除
function delFun(rebinId) {
    $("#delConfirm").modal({
        onConfirm: function () {
            $.ajax({
                type: "GET",
                url: "/resourceCombinationController/delResourceCombination?rebinId=" + rebinId,
                dataType: "json",
                success: function (data) {
                    if (data.result == "success") {
                        alert("删除成功！");
                        window.location.reload();
                    } else {
                        alert("删除失败！");
                    }
                },
                error: function () {
                    alert("发送请求失败");
                }
            });
        }
    });
}
